package cn.kgc.libraryapplication.service;

import cn.kgc.librarycommon.pojo.BookInfo;
import cn.kgc.librarycommon.pojo.Category;
import cn.kgc.librarycommon.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${book.rest.url}")
    private String bookUrl;

    @Value("${book.borrow.url}")
    private String borrowUrl;

    @Value("${book.category.url}")
    private String categoryUrl;

    @Value("${book.page.size}")
    private Integer pageSize;

    @Override
    public PageResult<BookInfo> getAllBooks(Integer pageNo, String bookName, String authorName) {
        String url = String.format("%s?pageNo=%d&pageSize=%d&bookName=%s&authorName=%s", bookUrl, pageNo, pageSize, bookName, authorName);
        System.out.println("url:"+url);
        return restTemplate.getForObject(url,PageResult.class);
    }

    @Override
    public List<Category> getAllCategory() {
        //类型擦除
        Category[] categories = restTemplate.getForObject(categoryUrl, Category[].class);
        return Arrays.asList(categories);
    }

    @Override
    public Integer borrow(Integer uid, Integer fid) {
        String url = String.format("%s?uid=%d&fid=%d", borrowUrl, uid, fid);
        return restTemplate.getForObject(url, Integer.class);
    }
}
